<?php

namespace app\admin\model;

use app\common\LogService;
use think\Model;

class Fake extends Model
{
    // 卡密类型常量
    const TYPE_VIP = 1;
    const TYPE_EXP = 2;
    const TYPE_COINS = 3;
    const TYPE_INVITE_CODE = 4;

    public function generateCards($type, $value, $count = 1)
    {
        $recordLog = function ($status, $message = '')  {
            LogService::record(
                name: '生成卡密',
                user_id: getAdminSessionVal(),
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
                user_type: 2

            );
        };
        // 验证参数
        if (!in_array($type, [self::TYPE_VIP, self::TYPE_EXP, self::TYPE_COINS, self::TYPE_INVITE_CODE])) {
            $recordLog(0,'无效的卡密类型');
            return ['code' => 0, 'msg' => '无效的卡密类型'];
        }
        if ($value <= 0 && $type != 4) {
            $recordLog(0,'卡密值必须大于0');
            return ['code' => 0, 'msg' => '卡密值必须大于0'];
        }
        if ($count <= 0) {
            $recordLog(0,'生成数量必须大于0');
            return ['code' => 0, 'msg' => '生成数量必须大于0'];
        }
        // 批量生成卡密
        $cards = [];
        $now = time();

        for ($i = 0; $i < $count; $i++) {
            $cards[] = [
                'fake' => randStr(16),
                'type' => $type,
                'value' => $value,
                'status' => 0,
                'create_time' => $now,
                'update_time' => $now
            ];
        }
        $res = $this->insertAll($cards);
        if ($res) {
            return ['code' => 200];
            $recordLog(1);
        } else {
            $recordLog(0,'生成失败');
            return ['code' => 0, 'msg' => '生成失败'];
        }
    }
}
